package com.smarttest.portal.refresh.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smarttest.portal.refresh.util.model.ApiResult;
import com.smarttest.portal.refresh.util.model.QueryParam;
import com.smarttest.portal.refresh.util.model.ResultData;
import com.smarttest.portal.refresh.util.model.Truck;


public class ShareTruckUtil {
	private final static Logger logger = LoggerFactory.getLogger(ShareTruckUtil.class);
	
	private static String APP_URL = "http://g7s.api.huoyunren.com/interface/index.php";
	private static String APP_KEY = "api_test";
	private static String APP_SECRET = "6dfe93f4ca39d8fae7da12af34300f89";
	private static String METHOD = "joint.truck.getShareTruck";
	/*
	 * 使用jackson进行json解析
	 */
	private static ObjectMapper mapper = new ObjectMapper();

	public static ApiResult getApiResult(QueryParam queryParam) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("app_key", APP_KEY);
		map.put("method", METHOD);
		map.put("data",queryParam);
		map.put("timestamp",
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		map.put("sign", sign(map, APP_SECRET));
		String params = createRequestParam(map);
		String jsonResult = getResult(APP_URL, params);
		ApiResult apiResult = null;
		try {
			apiResult = json2ApiResult(jsonResult);
		} catch (Exception e) {
			logger.warn("包含非法json字符: " + jsonResult + "\n" + e.getMessage());
		}
		return apiResult;
	}

	public static ResultData getResultData(QueryParam queryParam) {
		return getApiResult(queryParam).getData();
	}

	public static Truck[] getTrunks(QueryParam queryParam) {
		return getResultData(queryParam).getResult();
	}

	public static ApiResult json2ApiResult(String str)
			throws JsonParseException, JsonMappingException, IOException {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SerializationConfig serConfig = mapper.getSerializationConfig();
		serConfig.setDateFormat(dateFormat);
		DeserializationConfig deserializationConfig = mapper
				.getDeserializationConfig();
		deserializationConfig.setDateFormat(dateFormat);
		return mapper.readValue(str, ApiResult.class);
	}

	public static String createRequestParam(Map<String, Object> map) {
		StringBuilder param = new StringBuilder();

		for (Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it
				.hasNext();) {
			Map.Entry<String, Object> e = it.next();
			Object value = e.getValue();
			if (value != null) {
				param.append("&").append(e.getKey()).append("=").append(value);
			}
		}
		return param.toString().substring(1);
	}

	/*
	 * 签名方法，用于生成签名。
	 * 
	 * @param params 传给服务器的参数
	 * 
	 * @param secret 分配给您的APP_SECRET
	 */
	public static String sign(Map params, String secret) {
		String result = null;
		if (params == null)
			return result;

		// 将参数按key排序
		Set<String> keys = params.keySet();
		String[] ps = new String[keys.size()];
		int i = 0;
		for (String key : keys) {
			Object value = params.get(key);
			if (value != null) {
				ps[i++] = key + value.toString();
			}
		}
		if (i == 0)
			return result;
		String[] ss = new String[i];
		System.arraycopy(ps, 0, ss, 0, i);
		Arrays.sort(ss);

		// 将secret同时放在头尾，拼成字符串
		StringBuilder orgin = new StringBuilder(secret);
		for (int j = 0; j < ss.length; j++) {
			orgin.append(ss[j]);
		}
		orgin.append(secret);

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception ex) {
			throw new java.lang.RuntimeException("sign error !");
		}
		return result;
	}

	/*
	 * 二行制转字符串
	 */
	public static String byte2hex(byte[] b) {

		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	/*
	 * 得到返回的内容
	 */
	public static String getResult(String urlStr, String content) {
		URL url = null;
		HttpURLConnection connection = null;

		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setConnectTimeout(5000);
			connection.connect();

			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			out.writeBytes(content);
			out.flush();
			out.close();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}

}
